package net.jltec.api;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jltec.core.service.ICommonService;
import net.jltec.core.utils.Tools;
import net.jltec.model.util.RequestContext;

import org.apache.commons.lang.StringUtils;

public class OauthFilter implements Filter {

	public void destroy() {
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String oauth_token_secret = req.getParameter("oauth_token_secret");
		try {
			
			if(!StringUtils.isEmpty(oauth_token_secret)){
				ICommonService service = Tools.getCommonService();
				if(service!=null){
					String sql = "select * from t_sys_user a where '"+oauth_token_secret+"'=name+pass";
					Map m = service.dynamicQueryForMap(sql);
					if(m!=null&&!m.isEmpty()){
						int manid = (Integer) m.get("manid");
						RequestContext.beginAppLogonid(manid);
						chain.doFilter(request, response);// 验证通过则转向
					}
				}
			}else{
				String uri = req.getRequestURI();
				String ip = req.getRemoteAddr();
				System.out.println(ip);
				if(StringUtils.isNotEmpty(uri)&&uri.indexOf(("loginApp"))>0){
					chain.doFilter(request, response); 
				}
			}
			
		} catch (Exception e) {
			 
		}finally{
			RequestContext.end();
		}

	}

}